package com.sakura.controller;

import com.sakura.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        File file = new File(basePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String s = UUID.randomUUID() + multipartFile.getOriginalFilename();
        multipartFile.transferTo(new File(basePath + "/" + s));
        return R.success(s);
    }

    @GetMapping("/download")
    public byte[] download(@RequestParam("name") String name, HttpServletResponse response) throws IOException {
        // FileInputStream is = new FileInputStream(basePath + name);
        // ServletOutputStream os = response.getOutputStream();
        // IOUtils.copy(is,os);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basePath + name));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(bis, baos);
        return baos.toByteArray();
    }
}
